package com.xliang.spider.version02;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import com.xliang.db.DBUtil;
import com.xliang.spider.util.Video;
import com.xliang.spider.util.VideoUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

public class SpiderDownloadVideo extends Thread
{
    private static Connection conn = null;
    
    private String path;
    
    public SpiderDownloadVideo(String path)
    {
        this.path = path;
    }
    
    @Override
    public void run()
    {
        while (true)
        {
            downloadVideo();
            try
            {
                Thread.sleep(5000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
    
    public void downloadVideo()
    {
        List<Video> videos = VideoUtil.findUnDownloadVideo();
        for (Video video : videos)
        {
            if (video.getId() != video.getIndex())
            {
                video.setStatus(2);
                VideoUtil.updateVideo(video);
                continue;
            }
            if (video.getUrl().endsWith(".mp4"))
            {
                download(video);
            }
            else
            {
                video.setStatus(2);
                VideoUtil.updateVideo(video);
            }
        }
    }
    
    private void download(Video video)
    {
        OutputStream outStream = null;
        try
        {
            String fileName = String.format("%03d.%s", video.getIndex(), video.getName());
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(video.getUrl());
            HttpResponse response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                HttpEntity httpEntity = response.getEntity();
                File file = new File(path + fileName);
                if (file.exists())
                {
                    System.err.println(String.format("视频【%s】已经存在，跳过下载...", fileName));
                }
                else
                {
                    outStream = new FileOutputStream(file);
                    httpEntity.writeTo(outStream);
                    System.out.println(String.format("视频【%s】下载成功", fileName));
                }
                video.setStatus(1);
            }
            else
            {
                video.setStatus(2);
            }
        }
        catch (Exception e)
        {
            video.setStatus(2);
            e.printStackTrace();
            System.err.println(String.format("视频【%s】下载失败", video.getName()));
        }
        finally
        {
            VideoUtil.updateVideo(video);
            if (outStream != null)
            {
                try
                {
                    outStream.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public int downloadVideo(String videoName, String videoUrl)
    {
        int result = -1;
        InputStream inputStream = null;
        FileOutputStream outStream = null;
        try
        {
            String fileName = path + videoName;
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(videoUrl);
            HttpResponse response = client.execute(httpGet);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                HttpEntity httpEntity = response.getEntity();
                File file = new File(path + fileName);
                if (file.exists())
                {
                    System.out.println("视频：" + videoName + "已经存在，跳过下载");
                    return 1;
                }
                
                outStream = new FileOutputStream(file);
                httpEntity.writeTo(outStream);
                System.out.println(String.format("视频【%s】下载成功", fileName));
                result = 1;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (outStream != null)
            {
                try
                {
                    outStream.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (inputStream != null)
            {
                try
                {
                    inputStream.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            
        }
        return result;
    }
    
    public int downloadVideo2(String videoName, String videoUrl)
    {
        int result = -1;
        InputStream inputStream = null;
        FileOutputStream outStream = null;
        try
        {
            String fileName = path + videoName;
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(videoUrl);
            HttpResponse response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                File file = new File(fileName);
                if (file.exists())
                {
                    System.out.println("视频：" + videoName + "已经存在，跳过下载");
                    return 1;
                }
                outStream = new FileOutputStream(file);
                response.getEntity().writeTo(outStream);
                result = 1;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if (outStream != null)
                {
                    outStream.close();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return result;
    }
    
    public void queryVideo()
    {
        PreparedStatement pst1 = null;
        PreparedStatement pst2 = null;
        try
        {
            String sql = "select id,video_name,video_url from video where is_download=0 order by id limit 10";
            if (conn == null)
            {
                conn = DBUtil.open();
            }
            pst1 = conn.prepareStatement(sql);
            ResultSet rs = pst1.executeQuery();
            while (rs.next())
            {
                int id = rs.getInt("id");
                String videoName = rs.getString("video_name");
                String videoUrl = rs.getString("video_url");
                if (StringUtils.isNotEmpty(videoName) && StringUtils.isNotEmpty(videoUrl))
                {
                    if (videoUrl.endsWith(".mp4"))
                    {
                        long a = System.currentTimeMillis();
                        if (downloadVideo(videoName, videoUrl) > 0)
                        {
                            System.out.println("视频：" + videoName + "下载成功，耗时:" + ((System.currentTimeMillis() - a) / 1000) + "秒");
                            pst2 = conn.prepareStatement("delete from video where id=?");
                            pst2.setInt(1, id);
                            pst2.executeUpdate();
                        }
                        else
                        {
                            System.out.println("视频：" + videoName + "下载失败");
                            pst2 = conn.prepareStatement("update video set is_download=1 where id=?");
                            pst2.setInt(1, id);
                            pst2.executeUpdate();
                        }
                    }
                    else
                    {
                        System.out.println("视频：" + videoName + "地址不合法，跳过下载");
                        pst2 = conn.prepareStatement("update video set is_download=1 where id=?");
                        pst2.setInt(1, id);
                        pst2.executeUpdate();
                    }
                }
            }
            rs.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            DBUtil.close(pst1);
            DBUtil.close(pst2);
        }
    }
}
